package com.mysiteforme.admin.util;

import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.qiniu.util.UrlSafeBase64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;


@Component
public class QiNiuGetToken {

    @Value("${qiniu.watertext}")
    String waterText;

    @Value("${qiniu.waterfont}")
    String waterFont;

    //设置转码的队列
    @Value("${qiniu.pipeline}")
    String pipeline;

    //设置好账号的ACCESS_KEY和SECRET_KEY
    @Value("${qiniu.token.ak}")
    String ACCESS_KEY;
    @Value("${qiniu.token.sk}")
    String SECRET_KEY;

    //要上传的空间
    @Value("${qiniu.token.video_bucket}")
    String bucketname;

    //上传策略中设置persistentOps字段和persistentPipeline字段
    public String getUpToken(String key) {
        String wmText = UrlSafeBase64.encodeToString(waterText);
        String wmFont = UrlSafeBase64.encodeToString(waterFont);

        StringMap putPolicy = new StringMap();
        //回调的地址
        putPolicy.put("callbackUrl", "http://域名/common/qiniu/upload/callback");
        putPolicy.put("callbackBody", "filename=$(fname)&filesize=$(fsize)&mimeType=$(mimeType)");
        putPolicy.put("callbackBodyType", "application/json");
        long expireSeconds = 3600;
        Auth auth = Auth.create(ACCESS_KEY,SECRET_KEY);


        String fops = "avthumb/m3u8/noDomain/1/wmText/" + wmText + "/wmGravityText/South/wmFont/" + wmFont + "/wmFontSize/14";


        //可以对转码后的文件进行使用saveas参数自定义命名，当然也可以不指定文件会默认命名并保存在当前空间。
        String urlbase64 = UrlSafeBase64.encodeToString(bucketname + ":" + key);
        String pfops = fops + "|saveas/" + urlbase64;


        return auth.uploadToken(bucketname, null, 3600, new StringMap()
                .putNotEmpty("persistentOps", pfops)
                .putNotEmpty("persistentPipeline", pipeline), true);
    }

    /***
     * 删除已上传的视频
     * @param videoPath
     */
    public void deleteQiniuP(String videoPath) {
        Zone z = Zone.zone0();
        Configuration config = new Configuration(z);
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        BucketManager bucketManager = new BucketManager(auth,config);
        try {
            bucketManager.delete(bucketname, videoPath);
        } catch (QiniuException e) {
            e.printStackTrace();
        }
    }
}
